function renko(x,threshold)
%RENKO Renko chart.
%   RENKO(X) plots the asset data, X, in a Renko chart.   X is an Mx2
%   matrix where the first column contains date numbers and the second
%   column is the asset price.    
%
%   RENKO(X,THRESHOLD) plots the asset data, X, adding a new box only when
%   the price has changed but at least the value specified by THRESHOLD.
%   By default, THRESHOLD is set to 1.
%
%   See also BOLLING, CANDLE, HIGHLOW, LINEBREAK, MOVAVG, PRICEANDVOL, POINTFIG, KAGI, VOLAREA.

%	Copyright 1995-2007 The MathWorks, Inc.
%	$Revision: 1.1.6.2 $   $Date: 2007/11/22 16:40:05 $

%Set the default threshold
if nargin < 2
  threshold = 1;
end

%Preallocate kagi data and linewidth settings
numpoints = length(x(:,1));
if numpoints < 2 || (size(x,2) < 2)
  error('finance:renko:notEnoughData','Please specify at least two data points with corresponding dates.')
end

%Open a figure
curfig = figure; hold on

%Initialize the tick counter
tickstart = 0;

%Initialize the current price and date values
currentlevel = x(1,2);
currentdate = x(1,1);

%Initialize the date output vector used to label the x axis
xdatatotal = [];

%Get each trend line and set the marker face color to visually show
%positive (empty) or negative (filled) trends
for i = 1:numpoints-1
  if (abs(x(i+1,2) - currentlevel) >= threshold)
    data = fliplr(x(i+1,2):-threshold:currentlevel);
    datediff = x(i+1,1) - currentdate;
    xdata = fliplr(x(i+1,1):-datediff/length(data):currentdate);
    markerfacecolor = 'none';
    if isempty(data)
      data = fliplr(x(i+1,2):threshold:currentlevel);
      xdata = fliplr(x(i+1,1):-datediff/length(data):currentdate);
      markerfacecolor = 'black';
    end
    %If the price has move more than the threshold, add boxes
    if ~isempty(data)
      ticks = tickstart + (1:length(data));
      plot(ticks,data,'color','black','linestyle','none','marker','square','markerfacecolor',markerfacecolor)
      tickstart = ticks(end);
      currentlevel = x(i+1,2);
      currentdate = x(i+1,1);
    end
  
    %Store the dates for x axis labeling
    xdatatotal = [xdatatotal xdata(1:end-1)];
    
  end
end

%Trap case where no data displayed
if isempty(xdatatotal)
  close(curfig)
  error('finance:renko:noData','No data to display.')
end

%Build date string labels
set(gca,'xlim',[0 length(xdatatotal)])
xticks = round(get(gca,'XTick'));
xticks(xticks==0) = 1;
dates = xdatatotal(xticks);
datelabels = datestr(dates,1);

% %Axis settings
set(gca,'xgrid','on','ygrid','on','box','on','YAxisLocation','right','XTickLabel',datelabels)

%Place on axes
set(get(curfig,'Children'),'Tag','renkochart')


